/*动态计算表格高度*/
import { nextTick, onBeforeUnmount, onMounted, Ref, ref } from 'vue';

export function useElTableHeight(cardRef: Ref<any>, otherRefs: Ref<any>[]) {
  const tableHeight = ref(0);
  const calculateTableHeight = () => {
    const cardElement = cardRef.value?.$el || cardRef.value;
    if (cardElement instanceof HTMLElement) {
      let headerHeight;
      if ( otherRefs[0].value === 0) {
        headerHeight = 24;
      } else {
        headerHeight = otherRefs[0].value?.$el.getBoundingClientRect().height + 24;
      }
      let paginationHeight = -10;
      if (otherRefs.length > 1 && otherRefs[1].value?.$el.getBoundingClientRect().height !== 0) {
        paginationHeight = otherRefs[1].value?.$el.getBoundingClientRect().height;
      }
      const cardRect = cardElement.getBoundingClientRect();
      const windowHeight = window.innerHeight;
      tableHeight.value = windowHeight - cardRect.top - headerHeight - 12 - paginationHeight - 24;
    } else {
      console.warn('cardElement is not an HTMLElement');
    }
  };

  let resizeObserver: ResizeObserver | null = null;
  let intervalId: any = null;

  onMounted(async () => {
    await nextTick(); // 等待 DOM 更新
    calculateTableHeight();
    window.addEventListener('resize', calculateTableHeight);
    // 监听 cardRef 的高度变化
    const cardElement = cardRef.value?.$el || cardRef.value;
    if (cardElement instanceof HTMLElement) {
      resizeObserver = new ResizeObserver(calculateTableHeight);
      resizeObserver.observe(cardElement);
    }
    // 定时器，每秒检查一次高度
    intervalId = setInterval(() => {
      calculateTableHeight();
    }, 1000);
  });

  onBeforeUnmount(() => {
    window.removeEventListener('resize', calculateTableHeight);
    if (resizeObserver) {
      const cardElement = cardRef.value?.$el || cardRef.value;
      if (cardElement instanceof HTMLElement) {
        resizeObserver.unobserve(cardElement);
      }
      resizeObserver.disconnect();
    }
    if (intervalId) {
      clearInterval(intervalId);
    }
  });

  return {
    tableHeight
  };
}
